package com.soxing.braindata.service.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.soxing.braindata.dao.domain.request.SearchRequest;
import com.soxing.common.utils.response.MyPage;
import com.soxing.common.utils.response.WebResponse;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;

/**
 * @author :durango
 * @date :2022/6/11 15:05
 * @description 抽象管理服务
 */
public abstract class AbstractManager<T> implements IManager<T> {

    /**
     * 基础服务
     *
     * @return
     */
    public abstract IService<T> getService();

    /**
     * 封装搜索条件
     *
     * @return
     */
    public abstract LambdaQueryWrapper<T> wrapSearchRequest(SearchRequest request);

    @Override
    public WebResponse<Boolean> add(T obj) {
        return WebResponse.success(getService().save(obj));
    }

    @Override
    public WebResponse<Boolean> update(T obj) {
        return WebResponse.success(getService().updateById(obj));
    }

    @Override
    public WebResponse<T> getById(Integer id) {
        return WebResponse.success(getService().getById(id));
    }

    @Override
    public WebResponse<Boolean> deleteById(Integer id) {
        return WebResponse.success(getService().removeById(id));
    }

    @Override
    public WebResponse<MyPage<T>> search(SearchRequest request) {
        LambdaQueryWrapper<T> queryWrapper = wrapSearchRequest(request);
        Integer pageNum = request.getPageNum();
        Integer pageSize = request.getPageSize();
        if (pageNum == null || pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize == null || pageSize <= 0) {
            pageSize = 10;
        }
        Page<T> page = new Page<>(pageNum, pageSize);
        IPage<T> res = getService().page(page, queryWrapper);
        if (res == null || CollectionUtils.isEmpty(res.getRecords())) {
            return WebResponse.success(new MyPage<>(1, 0, 0, new ArrayList<>()));
        }
        return WebResponse.success(new MyPage<>(pageNum, res.getPages(), res.getTotal(), res.getRecords()));
    }
}
